#include "DataManager.h"
#include "CvsData.h"
#include "SqlStringMap.h"
#include "SqlDataManager.h"

DataManager::DataManager(void)
{
	initData();
}

DataManager::~DataManager(void)
{
	MapCvsData::iterator it1, it2;
	it1 = mMapCvsData.begin();
	it2 = mMapCvsData.end();
	for (; it1 != it2; ++it1)
	{
		delete it1->second;
	}
	mMapCvsData.clear();
}

CvsData* DataManager::getCvsData( const std::string& str )
{
	MapCvsData::iterator it = mMapCvsData.find(str);
	if (it == mMapCvsData.end())
	{
		CvsData* d = new CvsData();
		mMapCvsData.insert(std::make_pair(str, d));
		return d;
	}
	else return it->second;
}

void DataManager::initData( void )
{
	tools::MapString ::iterator it1, it2;
	it1 = tools::gMapString.begin();
	it2 = tools::gMapString.end();
	mCurData.clear();
	std::string name;
	CvsData* d = NULL;
	for (; it1 != it2; ++it1)
	{
		name = tools::getFileName(it1->first);
		d = getCvsData(name);
		d->setName(name);
		mCurData.insert(std::make_pair(name, d));
	}
}

bool DataManager::isData( const std::string& str )
{
	MapCvsData::iterator it = mCurData.find(str);
	if (it == mCurData.end())
	{
		return false;
	}
	return true;
}

void DataManager::save( const std::string& path )
{
	MapCvsData::iterator it1, it2;
	it1 = mCurData.begin();
	it2 = mCurData.end();
	for (; it1 != it2; ++it1)
	{
		it1->second->save(path);
	}
}

void DataManager::open( const std::string& path )
{
	MapCvsData::iterator it1, it2;
	it1 = mCurData.begin();
	it2 = mCurData.end();
	for (; it1 != it2; ++it1)
	{
		it1->second->openFile(path);
	}
}

CvsFile::VecVecstring& DataManager::getVecString( const std::string& str )
{
	MapCvsData::iterator it = mCurData.find(str);
	if (it != mCurData.end())
	{
		return it->second->getVecString();
	}
	static CvsFile::VecVecstring vec;
	return vec;
}

void DataManager::openFromSql( void )
{
	SqlDataManager* sql = SqlDataManager::getSingletonPtr();
	if (sql == NULL)
	{
		return;
	}
	MapCvsData::iterator it1, it2;
	it1 = mCurData.begin();
	it2 = mCurData.end();
	std::string str;
	for (;it1 != it2; ++it1)
	{
		str = tools::getSqlString(it1->first);
		if (!str.empty())
		{
			sql->getVecFromSql(str, it1->second->getVecString());
		}
	}
}
